package com.ruoyi.business.service.impl;

import com.ruoyi.business.dao.CustomerAddressDao;
import com.ruoyi.business.domain.CustomerAddress;
import com.ruoyi.business.service.ICustomerAddressService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * customer_addressService业务层处理
 *
 * @author liutietou
 * @since 1.0 2025-07-19
 */
@Transactional(readOnly = true)
@Service
public class CustomerAddressServiceImpl implements ICustomerAddressService {

    @Autowired
    private CustomerAddressDao customerAddressDao;
    @Autowired
    TokenService tokenService;

    /**
     * 查询customer_address
     *
     * @param id customer_addressID
     * @return customer_address
     */
    @Override
    public CustomerAddress findById(Integer id) {
        return customerAddressDao.findById(id).get();
    }

    /**
     * 分页查询customer_address列表
     *
     * @param req customer_address
     * @return customer_address
     */
    @Override
    public Page<CustomerAddress> findCustomerAddressPage(CustomerAddress req) {
        Specification<CustomerAddress> example = formatQueryParams(req);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Pageable pageable = PageRequest.of(pageDomain.getPageNo(),
                Optional.ofNullable(pageDomain.getPageSize()).orElse(PageDomain.DEFAULT_PAGE_SIZE),
                Sort.Direction.DESC,
                Optional.ofNullable(pageDomain.getOrderByColumn()).orElse("id"));
        Page<CustomerAddress> page = customerAddressDao.findAll(example, pageable);
        return page;
    }

    /**
     * 分页查询customer_address列表
     *
     * @param req customer_address
     * @return customer_address
     */
    @Override
    public List<CustomerAddress> findCustomerAddressList(CustomerAddress req) {
        Specification<CustomerAddress> example = formatQueryParams(req);
        List<CustomerAddress> list = customerAddressDao.findAll(example, Sort.by(Sort.Direction.ASC,"id"));
        return list;
    }

    private Specification<CustomerAddress> formatQueryParams(CustomerAddress req){
        Specification<CustomerAddress> example = new Specification<CustomerAddress>() {
            private static final long serialVersionUID = 1L;
            SysUser sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
            @Override
            public Predicate toPredicate(Root<CustomerAddress> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (null != req.getId()){
                    Predicate pre = cb.equal(root.get("id").as(Integer.class), req.getId());
                    list.add(pre);
                }
                if (StringUtils.isNotBlank(req.getAddress())){
                    Predicate pre = cb.like(root.get("address").as(String.class),"%"+ req.getAddress()+"%");
                    list.add(pre);
                }
                if (StringUtils.isNotBlank(req.getPhone())){
                    Predicate pre = cb.like(root.get("phone").as(String.class), "%"+ req.getPhone()+"%");
                    list.add(pre);
                }
                if (StringUtils.isNotBlank(req.getReceiver())){
                    Predicate pre = cb.like(root.get("receiver").as(String.class),"%"+ req.getReceiver()+"%");
                    list.add(pre);
                }

                if ( StringUtils.isNotBlank(req.getCcuscode())){
                    Predicate pre = cb.equal(root.get("ccuscode").as(String.class), req.getCcuscode());
                    list.add(pre);
                }
                if(!sysUser.isAdmin() && null != sysUser.getCust()){
                    Predicate pre = cb.equal(root.get("ccuscode").as(String.class), sysUser.getCust().getCcuscode());
                    list.add(pre);
                }

                if (null != req.getAreacode()){
                    Predicate pre = cb.equal(root.get("areacode").as(Long.class), req.getAreacode());
                    list.add(pre);
                }

                if (list.isEmpty()) {
                    return null;
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        return example;
    }

    /**
     * 保存（新增/修改）customer_address
     *
     * @param customerAddress customer_address
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(CustomerAddress customerAddress) {
        customerAddressDao.save(customerAddress);
    }


    /**
     * 批量删除customer_address
     *
     * @param ids 需要删除的customer_addressID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(List<Integer> ids) {
        List<CustomerAddress> existBeans = customerAddressDao.findAllById(ids);
        if(!existBeans.isEmpty()){
            customerAddressDao.deleteAll(existBeans);
        }
    }

    /**
     * 删除customer_address信息
     *
     * @param id customer_addressID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteCustomerAddressById(Integer id) {
         customerAddressDao.deleteById(id);
    }
}
